package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Alltickets;
import cn.wolfcode.trip.base.domain.Expense;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.AllticketsMapper;
import cn.wolfcode.trip.base.mapper.ExpenseMapper;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IAllticketsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AllticketsServiceImpl implements IAllticketsService {
    @Autowired
    private AllticketsMapper allticketsMapper;

    @Autowired
    private ExpenseMapper expenseMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void save(Alltickets alltickets) {
        alltickets.setPurchaseTime(new Date());
        User user = alltickets.getUser();


        if (alltickets.getUser().getId() == null) {
            //判断是否有用户登录
            throw new RuntimeException("请登录账号!");
        } else if (alltickets.getEffectiveTime() == null) {
            //判断是否填写日期
            throw new RuntimeException("请填写门票时间!");

        } else if (alltickets.getTakeName() == null) {
            //判断是否填写名称
            throw new RuntimeException("请填写取票名称!");
        } else if (alltickets.getPhone() == null) {
            //判断是否填写电话
            throw new RuntimeException("请填写电话,方便联系!");
        }
        //修改购买后的金额
        User u = userMapper.selectByPrimaryKey(user.getId());
        if (u.getBalance() < alltickets.getMoney()) {
            throw new RuntimeException("余额不足,请进行充值!");
        }
        userMapper.consumptionMoney(u.getId(), alltickets.getMoney());

        Expense e = new Expense();
        e.setConsumeTime(new Date());//消费时间
        e.setConsumeMoney(alltickets.getMoney());//消费金额
        e.setConsumeName(alltickets.getScenicName());//消费名称
        e.setConsumeType("门票");//消费类型
        e.setUser(user);//id
        //添加消费记录
        expenseMapper.insert(e);

        allticketsMapper.insert(alltickets);
    }

    @Override
    public void delete(Long id) {
        allticketsMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Alltickets> list = allticketsMapper.selectAll(qo);
        return new PageInfo(list);
    }
}
